package app.controller;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;

import app.exceptions.ChequeInvalidoException;
import app.file.FileManager;
import app.model.Cheque;

public class ChequeController implements Serializable {
	private static final long serialVersionUID = 1L;

	private static ChequeController unicaInstancia;

	public ArrayList<Cheque> cheques;
	private double taxaJuros = 0;

	public ChequeController() {
		cheques = new ArrayList<Cheque>();
	}

	public void addCheque(Cheque c) throws ChequeInvalidoException {

		for (Cheque ch : cheques)
			if (ch.getNome().equals(c))
				throw new ChequeInvalidoException("Nome ja existente");

		cheques.add(c);
	}
	
	public ArrayList<Cheque> getList() {
		return cheques;
	}

	public void removeCheque(String nome) throws ChequeInvalidoException {

		for (Cheque c : cheques) {
			if (c.getNome().equals(nome)) {
				cheques.remove(c);
				return;
			}
		}
		throw new ChequeInvalidoException("Nome nao existente");
	}

	public static ChequeController getInstance() {

		if (unicaInstancia == null)
			unicaInstancia = new ChequeController();

		return unicaInstancia;
	}

	public double getTaxaJuros() {
		return taxaJuros;
	}
	
	public void setTaxa(double novaTaxa) {
		taxaJuros = novaTaxa;
	}

	public Cheque getCheque(int chequeAtual) {
		
		if (chequeAtual < 0 || chequeAtual >= cheques.size())
			return cheques.get(0);
		
		return cheques.get(chequeAtual);
	}

	public void muda(int x, Cheque c) {
		
		if (c == null) {
			if (cheques.size() > x)
				cheques.set(x, null);
		} else {
			
			if (x < cheques.size())
				cheques.set(x, c);
			else {
				while (x >= cheques.size())
					cheques.add(null);
				
				cheques.set(x, c);
			}
		}
	}

	public static void save() {
		try {
		FileManager.salvarArquivo(unicaInstancia);
		} catch (IOException ioe) {
			System.out.println("Erro ao Salvar Arquivo: " + ioe.getLocalizedMessage());
		}
	}
	
	public static void load() {
		
		try {
			unicaInstancia = FileManager.carregarArquivo();
		} catch (IOException e) {
			System.out.println("Erro ao Carregar Arquivo: " + e.getLocalizedMessage());
		} catch (ClassNotFoundException e) {
			System.out.println("Arquivo Corrompido");
			e.printStackTrace();
		}
	}
}
